package registnet.util.schedule;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * An implementation of a schedule.
 */
public class Schedule {
	
	private Map<String,Day> days;
	
	/**
	 * Default constructor.
	 */
	public Schedule(){
		initialize();
	}
	
	@SuppressWarnings("serial")
	public void initialize(){
		days = new HashMap<String, Day>(){{
			put(Day.MONDAY, new Day(Day.MONDAY));
			put(Day.TUESDAY, new Day(Day.TUESDAY));
			put(Day.WEDNESDAY, new Day(Day.WEDNESDAY));
			put(Day.THURSDAY, new Day(Day.THURSDAY));
			put(Day.FRIDAY, new Day(Day.FRIDAY));
			put(Day.SATURDAY, new Day(Day.SATURDAY));
		}};
	}

	/**
	 * Returns the days of the week.
	 * @return
	 */
	public Map<String, Day> getDays() {
		return days;
	}
	
	/**
	 * Checks if the given schedule is in conflict with the schedule.
	 * @param schedule
	 * @return true if the given schedule is in conflict with the schedule, and false otherwise.
	 */
	public boolean isConflict(Schedule schedule){
		for(String day : days.keySet()){
			for(Task task : schedule.getDays().get(day).getTasks()){
				if(this.days.get(day).isConflict(task))
					return true;
			}
		}
		return false;
	}
	
	/**
	 * Checks if the schedule has a task. 
	 * @return true if the schedule has a task
	 */
	public boolean hasTask(){
		Iterator<String> di = days.keySet().iterator();
		while(di.hasNext())
			if(this.getDays().get(di.next()).getTasks().size()>0)
				return true;
		return false;
	}
	
	/**
	 * Returns a <code>String</code> representation of the schedule.
	 * @return a <code>String</code> representation of the schedule
	 */
	public String getRepresentation(){
		String retval = "";
		for (String dayString : days.keySet()) {
			retval = retval.concat(this.getDays().get(dayString).getDescription()+"\n");
			for(Task task : this.getDays().get(dayString).getTasks()){
				retval = retval.concat("\t"+task.getStartTime()+"-"+task.getEndTime()+"\n");
			}
		}
		return retval;
	}
	
	/**
	 * Combines the given schedule to the schedule.
	 * @param schedule
	 * @return the combination of the schedule and the given schedule.
	 */
	public Schedule combineSchedule(Schedule schedule){
		Schedule retval = new Schedule();
		for (String dayString : days.keySet()) {
			for(Task task : this.getDays().get(dayString).getTasks())
				retval.getDays().get(dayString).addTasks(task);
		}
		if(retval.isConflict(schedule)) return null;
		for (String dayString : days.keySet()) {
			for(Task task : schedule.getDays().get(dayString).getTasks())
				retval.getDays().get(dayString).addTasks(task);
		}
		return retval;
	}
	
}
